import { defineStore } from 'pinia'
import { ref } from 'vue'
import axios from 'axios'

export const useAuthStore = defineStore('auth', () => {
  const user = ref(null)
  const token = ref<string | null>(localStorage.getItem('token'))
  const isAuthenticated = ref(!!token.value)

  const login = async (username: string, password: string) => {
    try {
      const response = await axios.post('/api/login', { username, password })
      token.value = response.data.token
      user.value = response.data.user
      isAuthenticated.value = true
      if (token.value) localStorage.setItem('token', token.value)
      return true
    } catch (error) {
      console.error('Login failed:', error)
      return false
    }
  }

  const register = async (userData: any) => {
    try {
      const response = await axios.post('/api/register', userData)
      token.value = response.data.token
      user.value = response.data.user
      isAuthenticated.value = true
      if (token.value) localStorage.setItem('token', token.value)
      return true
    } catch (error) {
      console.error('Registration failed:', error)
      return false
    }
  }

  const logout = () => {
    user.value = null
    token.value = null
    isAuthenticated.value = false
    localStorage.removeItem('token')
  }

  return {
    user,
    token,
    isAuthenticated,
    login,
    register,
    logout
  }
}) 